// Simple MQTT publisher using mqtt_util
#include "mqtt_client.h"
#include "app_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    const char *host = (argc > 1) ? argv[1] : APPCFG_DEFAULT_MQTT_HOST;
    int port = (argc > 2) ? atoi(argv[2]) : APPCFG_DEFAULT_MQTT_PORT;
    const char *topic = (argc > 3) ? argv[3] : APPCFG_DEFAULT_PUB_TOPIC;
    const char *message;
    if (argc > 4) message = argv[4];
    else {
        fprintf(stderr, "Usage: %s [host] [port] [topic] <message>\n", argv[0]);
        fprintf(stderr, "Defaults: host=%s port=%d topic=%s\n", APPCFG_DEFAULT_MQTT_HOST, APPCFG_DEFAULT_MQTT_PORT, APPCFG_DEFAULT_PUB_TOPIC);
        return 1;
    }

    mqtt_config_t cfg; mqtt_config_from_env(&cfg);
    cfg.host = host; cfg.port = port;
    if (!(getenv("MQTT_WS_ENABLE") && *getenv("MQTT_WS_ENABLE"))) cfg.ws_enable = APPCFG_DEFAULT_WS_ENABLE ? true : false;
    if (!(getenv("MQTT_TLS_ENABLE") && *getenv("MQTT_TLS_ENABLE"))) cfg.tls_enable = APPCFG_DEFAULT_TLS_ENABLE ? true : false;
    if (cfg.ws_enable && !(getenv("MQTT_WS_PATH") && *getenv("MQTT_WS_PATH"))) cfg.ws_path = APPCFG_DEFAULT_WS_PATH;
    mqtt_client_t *cli = mqtt_client_new(&cfg, NULL);
    if (!cli) { fprintf(stderr, "OOM\n"); return 1; }
    int rc = mqtt_client_connect(cli);
    if (rc != 0) { fprintf(stderr, "Connect error: %s (host=%s port=%d)\n", mqtt_errstr(rc), host, port); mqtt_client_destroy(cli); return 1; }
    mqtt_client_start(cli);

    rc = mqtt_client_publish_sync(cli, topic, message, (int)strlen(message), 1, 0, 5000);
    if (rc != 0) fprintf(stderr, rc == -2 ? "Publish timeout\n" : "Publish error\n");

    mqtt_client_disconnect(cli);
    mqtt_client_stop(cli);
    mqtt_client_destroy(cli);
    return rc == 0 ? 0 : 2;
}
